package librus.codebase.packers;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.imageio.ImageIO;

import librus.codebase.util.FileUtil;

import de.innosystec.unrar.exception.RarException;


public class Unzip implements IPacker
{
	private ZipFile __archive;
	
	public LinkedList<String> getFiles(String path) throws RarException, IOException
	{
		LinkedList<String> result = new LinkedList<String>();
		File file = new File(path);
		
		if (!file.exists())			
			throw new FileNotFoundException("File not found");
			
		ZipFile zipFile = new ZipFile(file);

		Enumeration<?> entries = zipFile.entries();
		
		while (entries.hasMoreElements()) 
		{
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String name = entry.getName();
			if (FileUtil.isComicFile(name))
				result.add(name);				
		}		
	
		return result;
	}
	
	public Boolean openArchive(String archivePath)
	{
		Boolean result = false;
		try {			
			File file = new File(archivePath);
			
			if (!file.exists())			
				throw new FileNotFoundException("File not found");
						
			__archive = new ZipFile(file);
			result = true;
		} catch (IOException ioe) {
			System.err.println("Unhandled exception:");
			ioe.printStackTrace();
		}
		return result;
	}	
	
	public Boolean closeArchive()
	{
		Boolean result = false;
		try 
		{			
			__archive.close();
			result = true;
		} catch (IOException ioe) {
			System.err.println("Unhandled exception:");
			ioe.printStackTrace();
		}
		return result;
	}
	
	
	public BufferedImage getImage(String imageName)
	{
		BufferedImage image = null;
		
		try 
		{						
			ZipEntry imageEntry = __archive.getEntry(imageName);
			image = ImageIO.read(__archive.getInputStream(imageEntry));
		} catch (IOException ioe) {
			System.err.println("Unhandled exception:");
			ioe.printStackTrace();
		}
		
		return image;
	}
	
	

}
